import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  bool _isSending = false;
  int _seconds = 0;
  String? _errorText;

  @override
  void dispose() {
    _phoneController.dispose();
    _codeController.dispose();
    super.dispose();
  }

  bool _isPhoneValid(String phone) {
    // 简单的手机号正则校验
    return RegExp(r'^1[3-9]\d{9}$').hasMatch(phone);
  }

  void _startCountdown() {
    setState(() {
      _seconds = 30;
      _isSending = true;
    });
    Future.doWhile(() async {
      await Future.delayed(const Duration(seconds: 1));
      if (_seconds > 1) {
        setState(() {
          _seconds--;
        });
        return true;
      } else {
        setState(() {
          _seconds = 0;
          _isSending = false;
        });
        return false;
      }
    });
  }

  void _sendCode() {
    final phone = _phoneController.text.trim();
    if (!_isPhoneValid(phone)) {
      setState(() {
        _errorText = '请输入正确的手机号';
      });
      return;
    }
    setState(() {
      _errorText = null;
    });
    // TODO: 这里调用发送验证码的接口
    _startCountdown();
  }

  void _login() {
    final phone = _phoneController.text.trim();
    final code = _codeController.text.trim();
    if (!_isPhoneValid(phone)) {
      setState(() {
        _errorText = '请输入正确的手机号';
      });
      return;
    }
    if (code.length != 6) {
      setState(() {
        _errorText = '请输入6位验证码';
      });
      return;
    }
    setState(() {
      _errorText = null;
    });
    // TODO: 这里调用登录接口，校验验证码
    // 假设验证码为 123456
    if (code != '123456') {
      setState(() {
        _errorText = '验证码错误';
      });
      return;
    }
    // 登录成功，关闭页面
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录'),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        elevation: 0,
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 32),
            const Text('登录',
                style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            const Text('加入享+，让生活更轻松', style: TextStyle(fontSize: 16)),
            const SizedBox(height: 32),
            TextField(
              controller: _phoneController,
              keyboardType: TextInputType.phone,
              inputFormatters: [FilteringTextInputFormatter.digitsOnly],
              maxLength: 11,
              decoration: const InputDecoration(
                labelText: '手机号',
                counterText: '',
                border: UnderlineInputBorder(),
              ),
            ),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _codeController,
                    keyboardType: TextInputType.number,
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    maxLength: 6,
                    decoration: const InputDecoration(
                      labelText: '验证码',
                      counterText: '',
                      border: UnderlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                _isSending
                    ? Text('还剩${_seconds}秒',
                        style: const TextStyle(color: Colors.grey))
                    : TextButton(
                        onPressed: _isSending ? null : _sendCode,
                        child: const Text('发送验证码'),
                      ),
              ],
            ),
            const SizedBox(height: 8),
            const Text(
              '未注册手机号经验证后将自动登录',
              style: TextStyle(color: Colors.grey),
            ),
            if (_errorText != null) ...[
              const SizedBox(height: 8),
              Text(_errorText!, style: const TextStyle(color: Colors.red)),
            ],
            const Spacer(),
            SizedBox(
              width: double.infinity,
              height: 48,
              child: ElevatedButton(
                onPressed: _login,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF6CA6C1),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(24),
                  ),
                ),
                child: const Text('登录', style: TextStyle(fontSize: 20)),
              ),
            ),
            const SizedBox(height: 32),
          ],
        ),
      ),
    );
  }
}
